package cn.zyjw.config;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Configuration
@EnableConfigurationProperties(IdProperties.class)
public class IdAutoConfiguration {

    private static IdProperties idProperties;

    public IdAutoConfiguration(IdProperties idProperties) {
        IdAutoConfiguration.idProperties = idProperties;
    }

    private static RestTemplate restTemplate = new RestTemplate();

    public static boolean checkIdcard(String idCard, String name) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "APPCODE " + idProperties.getAppCode());
        String url = String.format(idProperties.getUrl(), idCard, name);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
        log.info("请求阿里身份验证返回: {}", response.toString());
        if (response.getStatusCode() == HttpStatus.OK) {
            String body = response.getBody();
            JSONObject jsonObject = JSON.parseObject(body);
            String status = jsonObject.getString("status");
            return "01".equals(status);
        }
        return false;
    }
}
